<?php

require($_SERVER['DOCUMENT_ROOT'] . "/bootstrap.php");
// kiểm tra xem login chưa, ai đăng nhập
if ($user_loginned == 'none') {
	echo '<script type="text/javascript">';
	echo 'alert("Bạn chưa đăng nhập!");';
	echo 'setTimeout("top.location.href =' . "'/login'" . '",0);';
	echo "</script>";
	die();
}
if ($user_loginned == 'user') {
	echo '<script type="text/javascript">';
	echo 'alert("Bạn không có quyền truy cập vào đây!");';
	echo 'setTimeout("top.location.href =' . "'/'" . '",0);';
	echo "</script>";
	die();
}
// end
if (isset($_GET['r']))
	$routing = $_GET['r'];
else
	$routing = "order";

// kiểm tra phân quyền: $user_loginned : none, user, staff, admin
//                      $user_loginned_staff: ketoan, banhang, ""
// vào dc đây là: staff (ketoan, banhang) + admin
if ($routing == 'order') {
	// giới hạn quyền
	if ($user_loginned_staff == "banhang") {
		echo '<script type="text/javascript">';
		echo 'alert("Bạn không có quyền vào meunu này!");';
		echo 'setTimeout("top.location.href =' . "'/admin/product'" . '",0);';
		echo "</script>";
		die();
	}
	//end
	// xử lí lưu
	if (isset($_POST['order_save'])) {
		foreach ($_POST['ordercode'] as $key => $value) {
			$orderdateship = new DateTime($_POST['orderdateship'][$key]);
			$sql = @"update listorder 
				set idstatus={$_POST['orderstatus'][$key]},
					orderdateship='{$orderdateship->getTimestamp()}'
				where ordercode = '{$_POST['ordercode'][$key]}'";
			mysql_query($sql);
		}
	}
	// end

	$listorder1 = mysql_query(@"
	SELECT * 
	FROM listorder li , STATUS st
	WHERE li.`idstatus` = st.`idstatus`
	ORDER BY orderdatecreate DESC");

	while ($row = mysql_fetch_array($listorder1)) {
		$listorder[] = $row;
	}
	$smarty->assign("listorder", $listorder);

	$status1 = mysql_query(@"
		SELECT *
		FROM status");
	while ($row = mysql_fetch_array($status1)) {
		$status[] = $row;
	}
	$smarty->assign("status", $status);
}

if ($routing == 'promotion') {
	// giới hạn quyền
	if ($user_loginned != "admin") {
		echo '<script type="text/javascript">';
		echo 'alert("Bạn không có quyền vào meunu này!");';
		if ($user_loginned_staff == "banhang")
			echo 'setTimeout("top.location.href =' . "'/admin/product'" . '",0);';
		else
			echo 'setTimeout("top.location.href =' . "'/admin/order'" . '",0);';
		echo "</script>";
		die();
	}
	//end
	$promotion1 = mysql_query(@"
		SELECT * FROM promotion p, category_promotion c WHERE p.idcategory=c.idcategory
	");
	while ($row = mysql_fetch_array($promotion1)) {
		$promotion[] = $row;
	}
	$promotion_category1 = mysql_query("select * from category_promotion");
	while ($row = mysql_fetch_array($promotion_category1)) {
		$promotion_category[] = $row;
	}
	$smarty->assign('category_promotion', $promotion_category);
	$smarty->assign('promotion', $promotion);

	//$error["promotionbytime"] = 0;
	// khuyến mãi theo thời gian, load thời gian bắt đầu, kết thúc, phần trăm khuyến mãi
	if (isset($_POST['submit'])) {
		$promotion_on_off = $_POST['promotion_on_off'];

		$datetimebegin = $_POST['datetimebegin'];
		list($month, $day, $year, $hour, $minute) = split('[/ :]', $datetimebegin);
		$datetimebegin = $year . "-" . $month . "-" . $day . " " . $hour . ":" . $minute . ":00";

		$datetimeend = $_POST['datetimeend'];
		list($month, $day, $year, $hour, $minute) = split('[/ :]', $datetimeend);
		$datetimeend = $year . "-" . $month . "-" . $day . " " . $hour . ":" . $minute . ":00";

		$percentdiscount = $_POST['percentdiscount'];

		//$date1 = new DateTime($datetimebegin);
		//$date2 = new DateTime($datetimeend);
		$query = "update promotion_time set `enable`={$promotion_on_off}";
		$result = mysql_query($query);
		$query = 'update promotion_time set `datebegin` ="' . "{$datetimebegin}" . '"';
		$result = mysql_query($query);
		$query = 'update promotion_time set `dateend` ="' . "{$datetimeend}" . '"';
		$result = mysql_query($query);
		$query = "update promotion_time set `percentdiscount`={$percentdiscount}";
		$result = mysql_query($query);
		//} else {
		//	$error["promotionbytime"] = 1;
		//}
		header('Location: /admin/promotion');
		exit();
	}
	//$smarty->assign('error', $error);
	// End - khuyến mãi
}

if ($routing == 'product') {
	// giới hạn quyền
	if ($user_loginned_staff == "ketoan") {
		echo '<script type="text/javascript">';
		echo 'alert("Bạn không có quyền vào meunu này!");';
		echo 'setTimeout("top.location.href =' . "'/admin/order'" . '",0);';
		echo "</script>";
		die();
	}
	//end
	$product1 = mysql_query(@"
		SELECT * FROM product p, category c WHERE p.idcategory=c.idcategory
	");
	while ($row = mysql_fetch_array($product1)) {
		$product[] = $row;
	}
	$category2 = mysql_query("select * from category c where c.parent!=0");
	while ($row = mysql_fetch_array($category2)) {
		$category3[] = $row;
	}
	$color1 = mysql_query("select * from color");
	while ($row = mysql_fetch_array($color1)) {
		$color[] = $row;
	}
	if (isset($_GET['action'])) {
		$action = $_GET['action'];
	}
	else
		$action = '';

	if ($action == 'addproduct') {	
		if(isset($_POST['createproduct']))
		{		
			$idcategory=$_POST['codeproduct'];
			$productname=$_POST['productname'];
			$warranty=$_POST['warranty'];
			$number=$_POST['number'];
			$colorinsert=$_POST['color'];
						
			$salepriece=$_POST['salepriece'];
			$promotion=$_POST['promotion'];
			$buypriece=$_POST['buypriece'];
			if( isset($_POST['newproduct']) && $_POST['newproduct']=='on'){
			$newproduct=1;}
			else{$newproduct=0;}
			
			$productdetail=$_POST['productdetail'];
			

			$sql = mysql_query(@"insert into product(productname,idcategory,price,price_company,promotion,warranty,productdetail,newproduct,inventory) values(
								'$productname',$idcategory,$buypriece,$salepriece,'$promotion','$warranty','$productdetail',$newproduct,$number)");
			//var_dump($sql);

			$sqlproduct=  mysql_query(@"SELECT idproduct FROM product ORDER BY  idproduct DESC  LIMIT 0,1");
			$rusult=  mysql_fetch_array($sqlproduct);
			$idproduct=$rusult[0];
			foreach($colorinsert as $item)
			{
			
				$sqlcolor=  mysql_query(@"insert into product_color (idproduct,idcolor) value($idproduct,$item)");

			}
			echo '<script type="text/javascript">';
			echo 'alert("Đã thêm sản phẩm!");';
			echo 'setTimeout("top.location.href =' . "'/admin/product/addproduct'" . '",0);';
			echo "</script>";
			die();
			//var_dump($sqlcolor);
		}
	}
	if ($action == 'edit') {
		
	}
	if (isset($_POST['savecategory'])) {

		if ($_POST['categorynamenew'] != "" && $_POST['linknew'] != "" && $_POST['parentnew'] != "") {

			$categoryname = $_POST['categorynamenew'];
			$linkname = $_POST['linknew'];
			$parentname = $_POST['parentnew'];

			$insertcategory = mysql_query("insert into category(categoryname,link,parent) value('$categoryname','$linkname','$parentname')");
			//var_dump($sql);
		}
	}
	$smarty->assign('category1', $category3);
	$smarty->assign('color', $color);
	$smarty->assign('product', $product);
//    if(isset($_POST['addoneproduct'])
//    {
//        $codeproduct=$_POST['codeproduct'];
//        $productname=$_POST['productname'];
//        
//    }
}

if ($routing == 'news') {
	// giới hạn quyền
	if ($user_loginned != "admin") {
		echo '<script type="text/javascript">';
		echo 'alert("Bạn không có quyền vào meunu này!");';
		if ($user_loginned_staff == "banhang")
			echo 'setTimeout("top.location.href =' . "'/admin/product'" . '",0);';
		else
			echo 'setTimeout("top.location.href =' . "'/admin/order'" . '",0);';
		echo "</script>";
		die();
	}
	//end
	$article1 = mysql_query(@"
   select * from article");
	while ($row = mysql_fetch_array($article1)) {
		$article[] = $row;
	}
	if (isset($_GET['action'])) {
		$action = $_GET['action'];
	}
	else
		$action = '';
	if ($action == 'addnew') {
		if (isset($_POST['savenew'])) {
			$title = $_POST['title'];
			$contentnew = $_POST['content'];

			$alias = $_POST['alias'];
			$datecreate = gmdate("d-m-Y | H:i", time() + 7 * 3600);
			$query = mysql_query("insert into article(title,content,datecreate,alias) value('$title','$contentnew','$datecreate','$alias')");
			$a = "insert into article(title,content,datecreate,alias) value('$title','$contentnew','$datecreate','$alias')";
		
			header('Location:/admin/news');
			exit();
		}
	}
	if($action=='delete')
	{
		if(isset($_GET['id']))
		{
			$idarticle=$_GET['id'];
			$sql=  mysql_query(@"delete from article where idarticle=$idarticle");
			
			header('Location:/admin/news');
			exit();
		}
		
	}
	$smarty->assign('article', $article);
	
}

if ($routing == 'user') {
	// giới hạn quyền
	if ($user_loginned != "admin") {
		echo '<script type="text/javascript">';
		echo 'alert("Bạn không có quyền vào meunu này!");';
		if ($user_loginned_staff == "banhang")
			echo 'setTimeout("top.location.href =' . "'/admin/product'" . '",0);';
		else
			echo 'setTimeout("top.location.href =' . "'/admin/order'" . '",0);';
		echo "</script>";
		die();
	}
	//end
	$user1 = mysql_query(@"
		select * from user u, permission p where u.idpermission=p.idpermission
	");
	while ($row = mysql_fetch_array($user1)) {
		$user[] = $row;
	}
	$permission1 = mysql_query(@"
		select * from permission
	");
	while ($row = mysql_fetch_array($permission1)) {
		$permission[] = $row;
	}

	$smarty->assign('permission', $permission);
	$smarty->assign('user', $user);

	if (isset($_GET['action'])) {
		$action = $_GET['action'];
	}
	else
		$action = '';

	if ($action == 'create') {

		if (isset($_POST['usercreate'])) {
			$email = $_POST['email'];
			$fullname = $_POST['fullname'];
			$phone = $_POST['phone'];
			$idaddress = $_POST['address'];
			$idpermission = $_POST['permission'];
			$password = md5('mpcamera');
			$founduser = 0;
			$sql = "select * from user where email='" . $email . "'";
			$query = mysql_query($sql);
			if (mysql_num_rows($query) != "") {
				$founduser = 2;
			}
			$smarty->assign("founduser", $founduser);
			$sql = mysql_query(@"insert into user(email,password,fullname,phone,address,idpermission) values(
								'$email',
								'$password',
								'$fullname',
								'$phone',
								'$address',								
								'$idpermission'
							)");
		}
		header('Location:/admin/user');
		exit();
	}
	if ($action == 'delete') {

		if (isset($_GET['id'])) {
			$user = $_GET['id'];
			$sql1 = mysql_query(@"select * from `user` where id=$user");
			$email = mysql_fetch_array($sql1);
			if ($session_email != $email[1]) {
				$sql = mysql_query(@"DELETE FROM `user` WHERE id=$user");
			}
		}
		header('Location:/admin/user');
		exit();
	}

	// xử lí save sửa permission của nhân viên
	if (isset($_POST['staff_save'])) {
		foreach ($_POST['staff_id'] as $key => $value) {
			$sql = @"update user 
					 set idpermission={$_POST['staff_permission'][$key]}
					 where id={$_POST['staff_id'][$key]}";
			mysql_query($sql);
		}
		header('Location:/admin/user');
		exit();
	}
	// end
}
if ($routing == 'ads') {
	// giới hạn quyền
	if ($user_loginned != "admin") {
		echo '<script type="text/javascript">';
		echo 'alert("Bạn không có quyền vào meunu này!");';
		if ($user_loginned_staff == "banhang")
			echo 'setTimeout("top.location.href =' . "'/admin/product'" . '",0);';
		else
			echo 'setTimeout("top.location.href =' . "'/admin/order'" . '",0);';
		echo "</script>";
		die();
	}
	//end
	if (isset($_POST['save_ads'])) {
		$slidegallery_id = $_POST['slidegallery_id'];
		$slidegallery_name = $_POST['slidegallery_name'];
		$slidegallery_link = $_POST['slidegallery_link'];
		foreach ($slidegallery_id as $slidegallery_id_item) {
			$ads_name = htmlentities($slidegallery_name[$slidegallery_id_item - 1], ENT_QUOTES);
			$ads_link = htmlentities($slidegallery_link[$slidegallery_id_item - 1], ENT_QUOTES);
			$sql = "update ads set name='{$ads_name}', link='{$ads_link}' where idads=$slidegallery_id_item";
			$query = mysql_query($sql);
		}
		// Upload logo
		foreach ($slidegallery_id as $slidegallery_id_item) {
			if ($_FILES['slidegallery_file']['name'][$slidegallery_id_item - 1] != '') {
				//var_dump()
				if (!is_dir('templates/images/ads/')) {
					mkdir('templates/images/ads/', 777, true);
				}
				$dir = "templates/images/ads/";
				chmod($dir, 777);
				$target_path = $dir . basename($_FILES['slidegallery_file']['name'][$slidegallery_id_item - 1]);

				$image_name = "qc$slidegallery_id_item." . pathinfo($target_path, PATHINFO_EXTENSION);
				$target_path = $dir . $image_name;
				//var_dump($target_path);
				if (!move_uploaded_file($_FILES['slidegallery_file']['tmp_name'][$slidegallery_id_item - 1], $target_path))
					$ads_upload_error = "Vui lòng thử lại";
				else
					echo "aaaaa";
				if ($_FILES['slidegallery_file']['size'][$slidegallery_id_item - 1] > (5 * 1024 * 1024)) {
					$ads_upload_error = "Tấm hình phải nhỏ hơn 5MB";
				}
				//var_dump($ads_upload_error);
			}
		}
		die();
	}
}

$smarty->assign('routing', $routing);
$smarty->display('../templates/admin/index.tpl');